const pageQuery = require('../utils/pageQuery')
const AsyncMysqljs = require('../mysql/index')
const Query = AsyncMysqljs().query

module.exports = async (ctx, next) => {
    const {page, pageSize, value} = ctx.request.query
    const sql = 'SELECT * FROM film_type'
    const typeList = await Query(sql)
    
    
    var init_page= page || 1; //默认页码为1
    var num = 20; //每页要显示的数据量
    
    var start = 0; //设置起始数据为第一条
    if(init_page>1) start = (init_page-1) * num; //页码减去1，乘以条数就得到分页的起始数了
    let filmListSql = ''
    let filmList = []
    let pageCount = 0
    const codeParams = 'id, pic_url, name, create_time'
    console.log(value);
    
    if(value) {
        filmListSql = `SELECT ${codeParams} FROM film WHERE type=? AND is_show=? ORDER BY id DESC limit ${start},${num}`
        filmList = await Query(filmListSql,[type, 1])
        pageCount = await Query('SELECT COUNT(*) FROM film WHERE type=? AND is_show=?', [value, 1])
        
        
    } else {
        filmListSql = `SELECT ${codeParams} FROM film WHERE is_show=? ORDER BY id DESC limit ${start},${num} `
        pageCount = await Query('SELECT COUNT(*) FROM film')
        filmList = await Query(filmListSql, [1])
    }
    console.log(filmList);
    // let res = await pageQuery({
    //     page: Number(page || 1),
    //     pageSize: Number(pageSize || 10),
    //     Model: Film,
    //     queryParams: queryData,
    //     populate: {},
    // })
    
    ctx.body = {
        code: 1,
        data: {
            filmType: typeList,
            filmList: filmList,
            page: init_page,
            pageSize: pageSize,
            pageCount: Math.ceil(pageCount[0]['COUNT(*)'] / num),
            total: pageCount[0]['COUNT(*)']
        },
        msg: 'ok'
    }
}